package com.open.jdbc.pool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentLinkedQueue;

public class ConnectionPool {

    //存放数据库连接Connection
    public ConcurrentLinkedQueue<Connection> connectionsPool = new ConcurrentLinkedQueue<>();
    //初始化连接个数
    private final int coreNumber = 2;

    //连接池最大容量
    private final int maxNumber = 10;

   public ConnectionPool() throws SQLException {
       init();
   }


   //初始化连接池
    public void init() throws SQLException {
        System.out.println(Thread.currentThread().getName()+"=== 初始化连接池 ====");
        for (int i = 0; i < coreNumber; i++) {
            Connection connection = createConnection();
            connectionsPool.add(connection);
        }
    }


    //提供给外部获取连接
    public synchronized Connection getConnection() throws SQLException {
        if (!connectionsPool.isEmpty()){
            System.out.println(Thread.currentThread().getName()+"=== 从连接池获取 ====");
            return connectionsPool.poll();
        }else {
            System.out.println(Thread.currentThread().getName()+"=== 临时创建连接 ====");
            return createConnection();
        }
    }

    //内部调用创建新的数据库连接
    private Connection createConnection() throws SQLException {
        Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
        return connection;
    }

    //回收连接进池子
    public synchronized void recycleConnection(Connection connection) throws SQLException {

        if(connection == null || connection.isClosed()){
            System.out.println(Thread.currentThread().getName()+"=== 丢弃失效 ====");
            return;
        }

        if(connectionsPool.size() <= maxNumber){
            //不超过连接池最大容量
            connection.setAutoCommit(true);
            System.out.println(Thread.currentThread().getName()+"=== 回收连接池 ====");
            connectionsPool.add(connection);
        }else {
            System.out.println(Thread.currentThread().getName()+"=== 连接丢弃关闭 ====");
            connection.close();
        }
    }

}
